package m2;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;

public class Producer {
    static String[] msgs = {
            "15103111039,创建",
            "15103111065,创建",
            "15103111039,付款",
            "15103117235,创建",
            "15103111065,付款",
            "15103117235,付款",
            "15103111065,完成",
            "15103111039,推送",
            "15103117235,完成",
            "15103111039,完成"
    };


    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //创建生产者，设置name server
        DefaultMQProducer p = new DefaultMQProducer("producerGroup2");
        p.setNamesrvAddr("192.168.64.141:9876");
        //启动
        p.start();
        //遍历消息，封装成Message对象
        //发送消息，需要指定队列选择器
        for (String msg : msgs) {
            // msg: "15103111039,创建"
            Long orderId = Long.valueOf(msg.split(",")[0]);
            Message message = new Message("Topic2", msg.getBytes());
            //p.send(message, 队列选择器, 用来执行队列选择运算的参数);
            p.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    // 第三个参数是选择依据，即orderId
                    Long orderId = (Long) arg;
                    // orderId对队列数量取余
                    int index = (int) (orderId % mqs.size());

                    return mqs.get(index);
                }
            }, orderId);
        }
    }
}
